package com.sls.mall.product.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.sls.mall.common.valid.AddGroup;
import com.sls.mall.common.valid.UpdateGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sls.mall.product.entity.BrandEntity;
import com.sls.mall.product.service.BrandService;
import com.sls.mall.common.utils.PageUtils;
import com.sls.mall.common.utils.R;



/**
 * 品牌
 *
 * @author tg
 * @email tg@gmail.com
 * @date 2021-04-24 16:14:45
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = brandService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
    public R info(@PathVariable("brandId") Long brandId){
		BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@Validated(value = {AddGroup.class}) @RequestBody BrandEntity brand
            //, BindingResult bindingResult
    ){

//        if (bindingResult.hasErrors())
//        {
//            HashMap<String, Object> map = new HashMap<>();
//
//            // 获取错误提示
//            bindingResult.getFieldErrors().stream().forEach((item) -> {
//
//                // 获取默认或者自定义的错误信息
//                String message = item.getDefaultMessage();
//
//                // 获取错误的属性名称
//                String field = item.getField();
//
//                map.put(field,message);
//            });
//
//            return R.error().put("data",map);
//        }else {
            brandService.save(brand);

            return R.ok();
//        }

    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@Validated(value = {UpdateGroup.class}) @RequestBody BrandEntity brand){
//		brandService.updateById(brand);

        //修改所有关联的冗余字段表

        brandService.updateDetail(brand);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] brandIds){
		brandService.removeByIds(Arrays.asList(brandIds));

        return R.ok();
    }

}
